﻿using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Sharp.Infrastructure.WebApiClient;
using Sharp.ServiceContracts;

namespace Sharp.WebBooter
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            WebApiServices
             .AddContract<IUserService>()
             .AddContract<IEnterpriseService>()
             .AddContract<IPlatformService>()
             .AddContract<IWorkflowService>()
             .AddContract<IOAuthService>().ConfigureWebApiConfig(() => new HttpApiConfig()
             {
                 HttpHost = new Uri("http://serv.abc.com/Platform/"),
                 ActionFilters = new IActionFilter[]
                 {
                                    new AuthorizationFilter()
                 }
             });


            config.Formatters.Remove(config.Formatters.XmlFormatter);

            //config.SuppressDefaultHostAuthentication();

            //要在http请求头中加上Bearer:Token
            //config.Filters.Add(new HostAuthenticationFilter("Bearer"));
            //config.Filters.Add(new HttpHeaderActionFilter());

            var serializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                MissingMemberHandling = MissingMemberHandling.Ignore,
                NullValueHandling = NullValueHandling.Include,
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                DefaultValueHandling = DefaultValueHandling.Include,
                Error = delegate (object obj, ErrorEventArgs args)
                {
                    //Errors.Add(args.ErrorContext.Error.Message);
                    args.ErrorContext.Handled = true;
                }
            };
            //解决时间毫秒精度太高，ie9或更低浏览器无法识别。
            IsoDateTimeConverter datetimeConverter = new IsoDateTimeConverter
            {
                DateTimeFormat = "yyyy/MM/dd HH:mm:ss"
            };
            serializerSettings.Converters.Add(datetimeConverter);
            config.Formatters.JsonFormatter.SerializerSettings = serializerSettings;


            config.MapHttpAttributeRoutes();
            //跨域配置
            //config.EnableCors(new EnableCorsAttribute("http://platform.abc.com", "*", "*"));
            config.Routes.MapHttpRoute(
                name: "webApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
        }
    }
}
